package com.gome.ai.aiparter.ws.test;

import com.alibaba.fastjson.JSON;
import com.gome.ai.aiparter.ws.enity.Conversation;
import org.java_websocket.WebSocket;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.PingFrame;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

public class WSServer extends WebSocketServer {

    public WSServer(int port){
        super(new InetSocketAddress(port));
    }

    public static void main(String[] args) {
        new WSServer(10906).start();
    }


    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        System.out.println("on Open");

        new Thread(() -> {
            int index = 0;
            while (true){
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                Conversation convV12 = Conversation.conv_v1_2;
                convV12.getMessages().add(new String[]{String.format("Write a phrase related to the number %s.",index++),null});
                webSocket.send(JSON.toJSONString(convV12));
            }
        }).start();
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        System.out.println("on Close");
    }

    @Override
    public void onMessage(WebSocket webSocket, String s) {
        System.out.println("on Message:" + s);
        String[] words = s.split(" ");
        for (String word : words) {
            webSocket.send(word);
        }
    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {

    }

    @Override
    public void onStart() {
        System.out.println("ws server on start port = " + getPort());
    }
}
